package com.dianping.cat.local.persistence;

import com.dianping.cat.message.spi.MessageCodec;
import com.dianping.cat.message.spi.MessageTree;
import com.dianping.cat.message.spi.codec.NativeMessageCodec;
import com.dianping.cat.message.spi.internal.DefaultMessageTree;
import com.dianping.cat.util.StringUtils;

import io.netty.buffer.ByteBuf;

/**
 * <p>
 * 日志入库 - 文件记录 - By CAT
 * 
 * @author LQ
 *
 */
public class CatLogService {

	// new PlainTextMessageCodec();
	private final MessageCodec ptmc;

	private final MessageBucketManager localMessageBucketManager;

	public CatLogService(MessageBucketManager localMessageBucketManager) {
		this(localMessageBucketManager, new NativeMessageCodec());
	}

	public CatLogService(MessageBucketManager localMessageBucketManager, MessageCodec ptmc) {
		this.localMessageBucketManager = localMessageBucketManager;
		this.ptmc = ptmc;
	}

	public void saveLog(MessageTree tree) {
		if (StringUtils.isEmpty(tree.getMessageId()) || StringUtils.isEmpty(tree.getFormatMessageId().toString())) {
			throw new RuntimeException("MessageTree的UD必须赋值");
		}

		ByteBuf bb = null;
		try {
			bb = ptmc.encode(tree);
			((DefaultMessageTree) tree).setBuffer(bb);
			localMessageBucketManager.storeMessage(tree, tree.getFormatMessageId());
		} catch (Exception ex) {
			throw ex;
		} finally {
			if (bb != null) {
				bb.release();
			}
		}
	}

	public MessageTree find(String traceId) {
		return localMessageBucketManager.loadMessage(traceId);
	}
}
